﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace System
{
    public static class ObjectHelper
    {
        public static T CopyTo<T>(this object source) where T : class
        {
            var pros = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);
            T result = System.Activator.CreateInstance<T>();
            foreach (var pro in pros)
            {
                var tpro = typeof(T).GetProperty(pro.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);
                if (tpro != null && pro.PropertyType == tpro.PropertyType)
                    tpro.SetValue(result, pro.GetValue(source, null), null);
            }
            return result;
        }

        public static T ConvertTo<T>(this object obj, T nullValue)
        {
            if (obj == null) return nullValue;
            if (obj is T)
                return (T)obj;
            return nullValue;
        }
    }
}
